﻿using Application.Common.Interfaces;
using Application.Features.Monitors.DTOs;
using Application.Features.Monitors.Specifications;
using AutoMapper;
using Common.Models;
using Domain.Entities.Loggers;
using MediatR;
using System.Text.Json.Serialization;
using System.Linq.Dynamic.Core;
using Common.Extensions;
using Common.Interfaces;
using Microsoft.EntityFrameworkCore;
using Common.Linqs;

namespace Application.Features.Monitors.Queries.Pagination;

public class LoggersWithPaginationQuery: LoggerAdvancedFilter, IRequest<PaginatedData<LoggerOutput>>
{
    public override string ToString()
    {
        return $"Search:{Keyword},StarTime:{StarTime},EndTime:{EndTime},Level:{Level},MessageTemplate:{MessageTemplate} {OrderBy}, {SortDirection}, {PageNumber}, {PageSize}";
    }

    [JsonIgnore]
    public LoggerAdvancedPaginationSpec Specification => new LoggerAdvancedPaginationSpec(this);

}

public class LogsWithPaginationQueryHandler :
         IRequestHandler<LoggersWithPaginationQuery, PaginatedData<LoggerOutput>>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUserService;
    private readonly IMapper _mapper;

    public LogsWithPaginationQueryHandler(
        IApplicationDbContext context,
        IMapper mapper,
        ICurrentUserService currentUserService)
    {
        _context = context;
        _mapper = mapper;
        _currentUserService = currentUserService;
    }

    public async Task<PaginatedData<LoggerOutput>> Handle(LoggersWithPaginationQuery request, CancellationToken cancellationToken)
    {
        if (_currentUserService.IsSystemAccount.HasValue && !_currentUserService.IsSystemAccount.Value)
        {
            request.UserName = _currentUserService.UserName;
        }

        return await _context.Loggers
            .OrderBy($"{request.OrderBy} {request.SortDirection}")
            .ProjectToPaginatedDataAsync<Logger, LoggerOutput>(
            request.Specification,
            request.PageNumber,
            request.PageSize,
            _mapper.ConfigurationProvider,
            cancellationToken);
    }
}